from django import forms
from django.contrib import auth
# Create your views here.
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.shortcuts import render

from black_market.models import Topic, create_user, UserProfile, Comment, Ware, Answer, Question


def index(request):
    return render(request, "index.html", {"exist": 0})


def userpage(request, username):
    user = User.objects.get(username=username)
    user_profile = UserProfile.objects.filter(user=user).first()
    bought_wares = user.bought_wares.all()
    sold_wares = user.sold_wares.all()
    gender = user_profile.gender
    nickname = user_profile.nickname
    questions = user.speaker_questions
    qq = user_profile.qq
    return render(request, "userpage.html", {"bought_wares": bought_wares,
                                             "sold_wares": sold_wares,
                                             "gender": gender,
                                             "nickname": nickname,
                                             "questions": questions,
                                             "qq": qq})


def ware(request):
    if request.GET:
        ware_name = request.GET.get("ware_name")
        current_ware = Ware.objects.get(name=ware_name)
        questions = current_ware.ware_questions.all()
        questions_answers_map = dict()

        for question in questions:
            questions_answers_map[question] = question.its_answers
        return render(request, "ware.html", {"ware": current_ware,
                                             "q_as": questions_answers_map,
                                             "questionCount": questions.count()})


def login(request):
    """
    something about errorCode:
    0 --> NO PROBLEM
    1 --> USER NOT FOUND
    2 --> PASSWORD ERROR

    """
    if request.POST:

        print(request.POST)
        loginDivShow = request.POST.get('loginDivShow', '')
        if loginDivShow == "true":
            #login part
            username = request.POST.get('login_username', '')
            password = request.POST.get('login_password', '')
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:

                auth.login(request, user)

                return HttpResponseRedirect("/userpage/" + str(username) + "/")
            else:
                try:
                    User.objects.get(username=username)
                    return render(request, "login.html", {"errorCode": 1})
                except Exception as e:
                    return render(request, "login.html", {"errorCode": 2})
        else:
            username = request.POST.get('signup-username', '')
            nickname = request.POST.get('signup-nickname', '')
            password = request.POST.get('signup-password', '')
            confirmed_password = request.POST.get('confirmed_password', '')
            gender = request.POST.get('signup-username', '')
            qq = request.POST.get('qq', '')
            create_user(username=username, password=password, gender=gender, qq=qq, nickname=nickname, )
        return render(request, "login.html", {"errorCode": 0})


def signup(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        nickname = request.POST.get('nickname', 'error')
        password = request.POST.get('password', '')
        confirm_password = request.POST.get('confirmed_password', '')
        gender_ = request.POST.get('gender', '')
        print("gender_: " + gender_)
        if gender_ == "male":
            gender = True
        elif gender_ == "female":
            gender = False
        else:
            print("gender: " + gender_)
            raise Exception()
        qq = request.POST.get('qq', '')
        if confirm_password == password:
            create_user(username=username, password=password, gender=gender, qq=qq, nickname=nickname)

            return render(request, "login.html")
    else:
        return render(request, "signup.html")


def forum(request):
    if request.is_ajax():
        new_topic = request.POST.get('topic', "")
        first_comment = request.POST.get('firstComment', '')
        if new_topic:
            topic = Topic.objects.create(title=new_topic, total_floor=1)
            Comment.objects.create(speaker=request.user, content=first_comment, response_target=-1, floor=1,
                                   topic=topic)
            info = {'successSubmitTopic': True}
            return JsonResponse(info)
    all_topics = Topic.objects.all()
    return render(request, "forum.html", {
        "all_topics": all_topics})


def topic(request, title: str):
    if title == 'ajax_topic':
        print("HAHA it is redirect to topic!")
    selected_topic = Topic.objects.get(title=title)

    if request.is_ajax():
        new_comment = request.POST.get("newComment", "")
        response = request.POST.get("response", "")
        comment_number = request.POST.get("commentNumber", "")
        print({"new_comment": new_comment, "response": response, "comment_number": comment_number})

        if new_comment:
            Comment.objects.create(speaker=request.user, content=new_comment, response_target=response,
                                   floor=comment_number, topic=selected_topic)
            info = {'successSubmitTopic': True}
            print("save finish")
            return JsonResponse(info)

    selected_topic = Topic.objects.get(title=title)

    if selected_topic is not None:
        ordered_comments = selected_topic.comments.all().order_by("floor")
        return render(request, "topic.html", {"title": title,
                                              "order_comments": ordered_comments})


def ajaxTopic(request):
    print(type(request.is_ajax()))
    if request.is_ajax():
        new_comment = request.POST.get("newComment", "")
        response = int(request.POST.get("response", ""))
        comment_number = int(request.POST.get("commentNumber", ""))
        in_topic = request.POST.get("topic")

        if new_comment:
            Comment.objects.create(speaker=request.user, content=new_comment, response_target=response,
                                   floor=comment_number, topic=in_topic)
            info = {'successSubmitTopic': "True"}
            return JsonResponse(info)


def shop(request):
    all_wares = Ware.objects.all()
    return render(request, "shop.html", {"wares", all_wares})
    # return render()


def get_request_ip(request) -> str:
    global ip
    try:
        ip = request.META['HTTP_X_FORWARDED_FOR']
    except:
        ip = request.META['REMOTE_ADDR']
    finally:
        return ip
